/**
 * 常用JS变量:
 * agentEvent = 代理模式下自动点击模块
 * acEvent= 无障碍模式下自动点击模块
 * device = 设备信息模块
 * file = 文件处理模块
 * http = HTTP网络请求模块
 * shell = shell命令模块
 * thread= 多线程模块
 * image = 图色查找模块
 * utils= 工具类模块
 * global = 全局快捷方式模块
 * 常用java变量：
 *  context : Android的Context对象
 *  javaLoader : java的类加载器对象
 * 导入Java类或者包：
 *  importClass(类名) = 导入java类
 *      例如: importClass(java.io.File) 导入java的 File 类
 *  importPackage(包名) =导入java包名下的所有类
 *      例如: importPackage(java.util) 导入java.util下的类
 *
 */
const common = require("common/index")
const jingling = require("myProject/精灵代挂.js")
const yuedu = require("myProject/阅读.js")
const timeList= [
    {h: 0, m: 1, method: wait},
    // {h: 0, m: 2, method: jingxiaohuInit},
    // {h: 1, m: 5, method: tianyiyunpan},
    //停止精灵代挂
    // {h: 9, m: 51, method: jinglingdaiguaStopFun},
    //爱茅台
    {h: 7, m: 2, method: startJingling},
    {h: 7, m: 20, method: wait},
    // {h: 23, m: 0, method: startZilong},
    // {h: 12, m: 31, method: startZilong},
    // {h: 14, m: 32, method: startJingling},

    //{h: 9, m: 52, method: iMaoTaiFun},
    //京东预约
    // {h: 10, m: 0, method: jingdongyuyueFun},
    //精灵代挂启动
    // {h: 10, m: 5, method: jinglingdaiguaStartFun},
    // {h: 11, m: 2, method: jingxiaohuInit},
    //精灵代挂停止
    // {h: 11, m: 58, method: jinglingdaiguaStopFun},
    //京东抢购
    // {h: 11, m: 59, method: jingdongqianggouFun},
    //精灵代挂启动
    // {h: 12, m: 10, method: jinglingdaiguaStartFun},
    // {h: 12, m: 6, method: wait},
    // {h: 14, m: 0, method: retartJinglingFun},

    // {h: 14, m: 0, method: retartJinglingFun},
    // {h: 16, m: 0, method: retartJinglingFun},
    // {h: 18, m: 0, method: retartJinglingFun},
    // {h: 20, m: 0, method: retartJinglingFun},
    // {h: 22, m: 0, method: retartJinglingFun},
    // {h: 19, m: 52, method: stopJingling},
    // {h: 17, m: 2, method: jingxiaohuInit},
    {h: 23, m: 59, method: wait}
];
let androidObj = ""
function main() {
    sleep(1000)
    setTimeout(() => {
        updateFun()
    }, 0)
    baohuo()
    // 获取设备对象
    androidObj = getDeviceObj()
    updateConfig("androidObj", JSON.stringify(androidObj))
    updateConfig("android", device.tcDeviceId())
    // 开启socket
    setTimeout(() => {
        startSocket(androidObj.num)
    }, 0)
    //检查权限
    checkAuth()

    var hours = new Date().getHours();
    jingling.stop()
    if (hours < 23 && hours >= 7) {
        jingling.start()
    } else {
        yuedu.start()
    }
    autoStart(timeList)


    // jingling.stop()
    //开始再这里编写代码了！！
    // toast("Hello World");
    // var name = readConfigString("name");
    // logd("姓名: " + name);
    // logd("年龄: " + readConfigString("age"));
    // logd("听音乐: " + readConfigString("music"));
    // logd("是不是一年级: " + readConfigString("one"));
    // logd("备注: " + readConfigString("mark"));
    // if (!autoServiceStart(3)) {
    //     logd("自动化服务启动失败，无法执行脚本")
    //     exit();
    //     return;
    // }
    // logd("开始执行脚本...")
    // if (!netcardProcessor()) {
    //     return;
    // }
    // home();
}


function startSocket(id) {
    let result = [];
    //新建一个ws连接
    var ws = http.newWebsocket("ws://47.242.237.113:3000/yuedu/socket", {}, 1);
    // 设置type=1的时候链接参数
    ws.setCallTimeout(5);
    ws.setReadTimeout(5);
    ws.setWriteTimeout(5);
    //心跳检测
    ws.setPingInterval(2)

    //设置type=2的时候心跳检测时间
    ws.setConnectionLostTimeout(5)
    //设置连接打开的时候监听器
    ws.onOpen(function(ws1, code, msg) {
        logi("onOpen code " + code + "  msg:" + msg);
        ws.sendText("ping")
    })
    //设置有文本信息监听器
    ws.onText(function(ws1, text) {
        logi(" onText " + text);
    })
    //设置关闭时候的监听器
    ws.onClose(function(ws1, code, reason) {
        logi(" onClose  " + code + "  reason : " + reason + " remote:");
    })
    ws.onError(function(ws1, msg) {
        logi(" onError  " + msg);
        result[0] = "error";
    })
    // bytes 是 java的bytes数组 对象
    ws.onBinary(function(ws1, bytes) {
        //转成java的
        logi(" onBinary  " + new java.lang.String(bytes));
    })

    //每3000 发送一次文本心跳数据
    // ws.startHeartBeat(function () {
    //     return null;
    // }, function () {
    //     return new Date().toISOString();
    // }, 3000, true);


    // ws.startHeartBeat(function () {
    //     return new java.lang.String("testXXX").getBytes();
    // }, function () {
    //     return null;
    // }, 3000, true);

    //停止发送心跳
    //ws.stopHeartBeat()

    //开始连接   阻塞的
    let r = ws.connect(10000);
    //设置自动重连
    ws.setAutoReconnect(true);
    logd("connect {} rr = {}", result[0], r);

    while (true) {
        // logd("isconnect " + ws.isConnected());
        sleep(3000)
        // if (ws.isConnected()) {
            // b = ws.sendText("new Date-" + new Date())
            // b = ws.sendText("ping")
            // logd("send =" + b);
        // } else {
            //重置链接
            //                let reset = ws.reset();
            //                logd("reset {}",reset)
            //                if (reset) {
            //                    logd("开始重连...");
            //                    let rc = ws.connect(10000);
            //                    logd("重连--"+rc);
            //                }
        // }
    }
    // logd("isClosed " + ws.isClosed())
    // sleep(1000)
    //关闭连接
    ws.close();
}

function baohuo() {
    device.keepScreenOn()
    daemonEnv(true)
}
function checkAuth() {
    image.requestScreenCapture(10000,0)
    if (!hasFloatViewPermission()) {
        requestFloatViewPermission(10)
    }
    sleep(3000)
    common.findClick("txt", "允许")
    sleep(1000)
    common.findClick("id", "android:id/switch_widget")
    // let
    //     per=[
    //         "android.permission.READ_CALENDAR",
    //         "android.permission.READ_SMS"
    //     ]
    // requestRuntimePermission(per,10000)
    // var selector = checked(true);
    // let times = 0
    // while(times < 20) {
    //     times++
    //     console.log("检查权限")
    //     const nodeInfo = id("android:id/switch_widget").getNodeInfo(1000)
    //     if (!nodeInfo[0].checked){
    //         common.findClick("id", "android:id/switch_widget")
    //         sleep(500)
    //         back()
    //     }
    //     common.findClick("txt", "允许")
    //     sleep(500)
    // }
}
function getDeviceObj() {
    const res = http.request({url: common.baseUrl + "/getDeviceList"})
    if (res) {
        const deviceList = JSON.parse(res.body).deviceList
        const android = device.tcDeviceId()
        logd(android)
        const res1 = deviceList.find(item => item.android == android) || null
        return res1
    } else {
        // toast("请求deviceList失败")
        console.log("请求deviceList失败")
        restartScript(null,true,3)
        return null
    }

}
function updateFun() {
    //请求服务器是否有新版本
    let version = 7;
    toast("Hello World - " + version);
    //请求服务器是否有新版本
    let updateResult = hotupdater.updateReq();
    logd("请求更新是否有: " + updateResult);
    if (!updateResult) {
        logw("请求失败错误信息: " + hotupdater.getErrorMsg());
    } else {
        logd("请求数据: " + hotupdater.getUpdateResp());
        //有更新得情况下进行下载新的版本
        let path = hotupdater.updateDownload();
        logd("下载路径为: " + path);
        if (!path) {
            logw("下载IEC文件错误信息: " + hotupdater.getErrorMsg());
        } else {
            restartScript(path, true, 3)
            return;
        }
    }
    sleep(10000);
    updateFun()
}
function netcardProcessor() {
    logd("开始进行卡密验证")
    // 官方自带的卡密系统
    // appId 和 appSecret的值 请到 http://uc.ieasyclick.com/ 进行注册后提卡
    let appId = "";
    let appSecret = "";
    let cardNo = readConfigString("cardNo")
    if (cardNo == null || cardNo == undefined || cardNo.length <= 0) {
        toast("请输入卡密")
        loge("请输入卡密")
        exit()
        return false;
    }
    let inited = ecNetCard.netCardInit(appId, appSecret)
    if (!inited) {
        toast("初始化卡密失败")
        exit();
        return false;
    }
    let bind = ecNetCard.netCardBind(cardNo)
    let bindResult = false;
    if (bind != null && bind != undefined && bind["code"] == 0) {
        logd("卡密绑定成功")
        let leftDays = bind['data']['leftDays'] + "天";
        logd("剩余时间：" + leftDays);
        logd("激活时间：" + bind['data']['startTime'])
        logd("过期时间：" + bind['data']['expireTime'])
        bindResult = true;
        toast("卡密剩余时间:" + leftDays)
    } else {
        if (bind == null || bind == undefined) {
            loge("卡密绑定失败,无返回值 ")
            let msg = "卡密绑定失败,无返回值"
            loge(msg)
            toast(msg)
        } else {
            let msg = "卡密绑定失败: " + bind["msg"]
            loge(msg)
            toast(msg)
        }
    }
    return bindResult;
}

function autoServiceStart(time) {
    for (var i = 0; i < time; i++) {
        if (isServiceOk()) {
            return true;
        }
        var started = startEnv();
        logd("第" + (i + 1) + "次启动服务结果: " + started);
        if (isServiceOk()) {
            return true;
        }
    }
    return isServiceOk();
}
function autoStart(timeList) {
    // 获取当前时间的步骤
    let step = common.getStep(timeList);
    console.log("=====定时方法", timeList[step].method);
    timeList[step].method();
    if (step + 1 <= timeList.length) {
        console.log("================getWaitTime")
        sleep(common.getWaitTime(timeList[step + 1].h, timeList[step + 1].m));
        autoStart(timeList);
    } else {
        toast("脚本执行完毕");
    }
}
function startJingling() {
    jingling.stop()
    sleep(2000)
    jingling.start()
}
function wait() {

}
main();
